using UnityEngine;
using System.Collections;

public class GameManager : MonoBehaviour
{
    [Header("游戏状态")]
    public GameState currentState = GameState.Menu;
    public float gameTime = 0f;
    public int score = 0;
    public int playerLives = 3;
    
    [Header("游戏设置")]
    public float adDuration = 40f; // 广告时长
    public bool autoStart = true;
    public bool showDebugInfo = true;
    
    [Header("引用组件")]
    public PlayerController playerController;
    public EnemySpawner enemySpawner;
    public TreasureSpawner treasureSpawner;
    public BoundaryManager boundaryManager;
    public BackgroundManager backgroundManager;
    
    [Header("预制体引用")]
    public GameObject playerPrefab;
    
    // 单例模式
    public static GameManager Instance { get; private set; }
    
    // 事件系统
    public System.Action<int> OnScoreChanged;
    public System.Action<int> OnLivesChanged;
    public System.Action<GameState> OnGameStateChanged;
    public System.Action OnGameOver;
    public System.Action OnGameWin;
    public System.Action OnPlayerDied;
    
    private float stateTimer;
    private bool isPaused = false;
    
    public enum GameState
    {
        Menu,
        Playing,
        Paused,
        GameOver,
        Victory,
        AdPlaying
    }
    
    void Awake()
    {
        // 单例模式实现
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
            return;
        }
    }
    
    void Start()
    {
        InitializeGame();
        
        if (autoStart)
        {
            StartCoroutine(AutoStartSequence());
        }
    }
    
    void Update()
    {
        if (isPaused) return;
        
        UpdateGameTime();
        HandleInput();
        UpdateGameLogic();
        
        if (showDebugInfo)
        {
            // Debug.Log($"游戏状态: {currentState}, 时间: {gameTime:F1}s, 分数: {score}, 生命: {playerLives}");
        }
    }
    
    void InitializeGame()
    {
        // 查找或创建必要的组件
        FindOrCreateComponents();
        
        // 初始化游戏状态
        score = 0;
        playerLives = 3;
        gameTime = 0f;
        
        // 设置摄像机
        SetupCamera();
        
        Debug.Log("游戏管理器已初始化");
    }
    
    void FindOrCreateComponents()
    {
        // 查找边界管理器
        if (boundaryManager == null)
        {
            boundaryManager = FindObjectOfType<BoundaryManager>();
            if (boundaryManager == null)
            {
                GameObject boundaryObj = new GameObject("BoundaryManager");
                boundaryManager = boundaryObj.AddComponent<BoundaryManager>();
            }
        }
        
        // 查找背景管理器
        if (backgroundManager == null)
        {
            backgroundManager = FindObjectOfType<BackgroundManager>();
            if (backgroundManager == null)
            {
                GameObject backgroundObj = new GameObject("BackgroundManager");
                backgroundManager = backgroundObj.AddComponent<BackgroundManager>();
            }
        }
        
        // 查找敌人生成器
        if (enemySpawner == null)
        {
            enemySpawner = FindObjectOfType<EnemySpawner>();
            if (enemySpawner == null)
            {
                GameObject spawnerObj = new GameObject("EnemySpawner");
                enemySpawner = spawnerObj.AddComponent<EnemySpawner>();
            }
        }
        
        // 查找宝箱生成器
        if (treasureSpawner == null)
        {
            treasureSpawner = FindObjectOfType<TreasureSpawner>();
            if (treasureSpawner == null)
            {
                GameObject treasureSpawnerObj = new GameObject("TreasureSpawner");
                treasureSpawner = treasureSpawnerObj.AddComponent<TreasureSpawner>();
            }
        }
        
        // 查找或创建玩家
        if (playerController == null)
        {
            playerController = FindObjectOfType<PlayerController>();
            if (playerController == null)
            {
                CreatePlayer();
            }
        }
    }
    
    void CreatePlayer()
    {
        GameObject player;
        
        if (playerPrefab != null)
        {
            // 使用预制体创建玩家，预制体已包含所有必需组件
            player = Instantiate(playerPrefab);
            Debug.Log("使用预制体创建玩家");
              // 设置玩家标签和位置
            player.tag = "Player";
            player.transform.position = new Vector3(0, -4f, 0);
            
            // 获取玩家控制器引用
            playerController = player.GetComponent<PlayerController>();
            
            Debug.Log("玩家创建完成，位置: " + player.transform.position);
        }
    }
    
    void SetupCamera()
    {
        Camera mainCamera = Camera.main;
        if (mainCamera == null)
        {
            GameObject cameraObj = new GameObject("Main Camera");
            mainCamera = cameraObj.AddComponent<Camera>();
            cameraObj.tag = "MainCamera";
        }
        
        // 设置为2D正交摄像机
        mainCamera.orthographic = true;
        mainCamera.orthographicSize = 5f;
        mainCamera.transform.position = new Vector3(0, 0, -10);
        mainCamera.backgroundColor = Color.black;
        
        Debug.Log("摄像机已配置为2D模式");
    }
    
    IEnumerator AutoStartSequence()
    {
        yield return new WaitForSeconds(1f);
        StartGame();
    }
    
    void UpdateGameTime()
    {
        if (currentState == GameState.Playing || currentState == GameState.AdPlaying)
        {
            gameTime += Time.deltaTime;
            
            // 检查广告时长
            if (currentState == GameState.AdPlaying && gameTime >= adDuration)
            {
                EndGame(true); // 广告播放完成，游戏胜利
            }
        }
    }
    
    void HandleInput()
    {
        // ESC键暂停/恢复游戏
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            if (currentState == GameState.Playing)
            {
                PauseGame();
            }
            else if (currentState == GameState.Paused)
            {
                ResumeGame();
            }
        }
        
        // R键重新开始
        if (Input.GetKeyDown(KeyCode.R))
        {
            RestartGame();
        }
    }
    
    void UpdateGameLogic()
    {
        switch (currentState)
        {
            case GameState.Playing:
                // 检查玩家是否死亡
                if (playerLives <= 0)
                {
                    EndGame(false);
                }
                break;
                
            case GameState.AdPlaying:
                // 广告播放逻辑
                break;
        }
    }
    
    public void StartGame()
    {
        ChangeGameState(GameState.Playing);
        gameTime = 0f;
        
        // 启用各个系统
        if (treasureSpawner != null)
        {
            treasureSpawner.enabled = true;
        }
        
        Debug.Log("游戏开始");
    }
    
    public void PauseGame()
    {
        ChangeGameState(GameState.Paused);
        isPaused = true;
        Time.timeScale = 0f;
        
        Debug.Log("游戏暂停");
    }
    
    public void ResumeGame()
    {
        ChangeGameState(GameState.Playing);
        isPaused = false;
        Time.timeScale = 1f;
        
        Debug.Log("游戏恢复");
    }
    
    public void RestartGame()
    {
        // 重置游戏状态
        score = 0;
        playerLives = 3;
        gameTime = 0f;
        isPaused = false;
        Time.timeScale = 1f;
        
        // 清理场景
        ClearScene();
        
        // 重新初始化
        InitializeGame();
        StartGame();
        
        Debug.Log("游戏重新开始");
    }
    
    public void EndGame(bool victory)
    {
        if (victory)
        {
            ChangeGameState(GameState.Victory);
            OnGameWin?.Invoke();
            Debug.Log("游戏胜利！");
        }
        else
        {
            ChangeGameState(GameState.GameOver);
            OnGameOver?.Invoke();
            Debug.Log("游戏结束！");
        }
        
        // 停止宝箱生成
        if (treasureSpawner != null)
        {
            treasureSpawner.enabled = false;
        }
    }
    
    void ClearScene()
    {
        // 清理敌人
        GameObject enemyContainer = GameObject.Find("Enemies");
        if (enemyContainer != null)
        {
            foreach (Transform child in enemyContainer.transform)
            {
                Destroy(child.gameObject);
            }
        }
        
        // 清理子弹
        GameObject[] bullets = GameObject.FindGameObjectsWithTag("PlayerBullet");
        foreach (GameObject bullet in bullets)
        {
            Destroy(bullet);
        }
        
        GameObject[] enemyBullets = GameObject.FindGameObjectsWithTag("EnemyBullet");
        foreach (GameObject bullet in enemyBullets)
        {
            Destroy(bullet);
        }
    }
    
    void ChangeGameState(GameState newState)
    {
        if (currentState != newState)
        {
            GameState oldState = currentState;
            currentState = newState;
            stateTimer = 0f;
            
            OnGameStateChanged?.Invoke(newState);
            Debug.Log($"游戏状态改变: {oldState} -> {newState}");
        }
    }
    
    
    // 公共访问方法
    public float GetGameTime() => gameTime;
    public int GetScore() => score;
    public int GetPlayerLives() => playerLives;
    public int GetLives() => playerLives;
    public GameState GetGameState() => currentState;
    public GameState GetCurrentState() => currentState;
    public bool IsGamePlaying() => currentState == GameState.Playing;
    
    // 事件触发方法
    public void HandlePlayerDied()
    {
        OnPlayerDied?.Invoke();
        Debug.Log("玩家死亡事件触发");
    }
    
    // 游戏状态控制方法
    public void SetGameState(GameState newState)
    {
        ChangeGameState(newState);
    }
    
    // UI控制方法
    public void ShowMainMenu()
    {
        ChangeGameState(GameState.Menu);
        Debug.Log("显示主菜单");
    }
}